<template>
  <section class="loginContainer">
    <div class="loginInner">
      <div class="login_header">
        <h2 class="login_logo">硅谷外卖</h2>
        <div class="login_header_title">
          <a href="javascript:;" :class="{on : phoneLogin}" @click="phoneLogin = !phoneLogin">短信登录</a>
          <a href="javascript:;" :class="{on : !phoneLogin}" @click="phoneLogin = !phoneLogin">密码登录</a>
        </div>
      </div>
      <div class="login_content">
        <form>
          <div :class="{on: phoneLogin}">
            <section class="login_message">
              <input type="tel" maxlength="11" placeholder="手机号" v-model.number="phone" name="phone" v-validate="{required: true,regex: /^1\d{10}$/}" autocomplete="off">
              <button :disabled="!isRightPhone || countDownTime > 0" class="get_verification" 
                :class="{'btn_code_active': isRightPhone}" @click.prevent="getPhoneCode">
                {{countDownTime ===0 ? '获取验证码': '已发送验证码('+ countDownTime +'s)'}}
              </button>
              <span style="color: red;" v-show="errors.has('phone')">{{ errors.first('phone') }}</span>
            </section>
            <section class="login_verification">
              <input type="tel" maxlength="8" placeholder="验证码" name="code" v-validate="'required'" v-model="code">
              <span style="color: red;" v-show="errors.has('code')">{{ errors.first('code') }}</span>
            </section>
            <section class="login_hint">
              温馨提示：未注册硅谷外卖帐号的手机号，登录时将自动注册，且代表已同意
              <a href="javascript:;">《用户服务协议》</a>
            </section>
          </div>
          <div :class="{on: !phoneLogin}">
            <section>
              <section class="login_message">
                <input type="tel" maxlength="11" placeholder="手机/邮箱/用户名" name="username" v-validate="'required'" v-model="username">
                <span style="color: red;" v-show="errors.has('username')">{{ errors.first('username') }}</span>
              </section>
              <section class="login_verification">
                <input :type="isShowPwd ? 'text' : 'password'" maxlength="8" placeholder="密码" name="pwd" v-validate="'required'" v-model="pwd">
                <div class="switch_button" :class="isShowPwd ? 'on' : 'off'" @click="isShowPwd = !isShowPwd">
                  <div class="switch_circle" :class="{'circle_right': isShowPwd}"></div>
                  <span class="switch_text">{{isShowPwd ? 'abc' : '...'}}</span>
                </div>
                <span style="color: red;" v-show="errors.has('pwd')">{{ errors.first('pwd') }}</span>
              </section>
              <section class="login_message">
                <input type="text" maxlength="11" placeholder="验证码" name="captcha" v-validate="'required'" v-model="captcha">
                <img class="get_verification" src="http://localhost:4000/captcha" alt="captcha" 
                  @click="getVerificationCode" ref="captcha"
                >
                <span style="color: red;" v-show="errors.has('captcha')">{{ errors.first('captcha') }}</span>
              </section>
            </section>
          </div>
          <button class="login_submit" @click.prevent="loginIn">登录</button>
        </form>
        <a href="javascript:;" class="about_us">关于我们</a>
      </div>
      <a href="javascript:" class="go_back" @click="$router.back()">
        <i class="iconfont icon-jiantou2"></i>
      </a>
    </div>
  </section>
</template>

<script>
import { MessageBox, Toast  } from 'mint-ui';
import {reqSMSCode, reqLoginByUsername, reqLoginBySMS} from '../../api'
export default {
  data () {
    return {
      // 登录切换显示
      phoneLogin: true,
      //  手机号
      phone: '',
      // 手机验证码
      code: '',
      // 用户账号
      username:'admin',
      // 用户密码
      pwd: '123456',
      // 图片验证码
      captcha: '',
      // 验证码倒计时
      countDownTime: 0,
      // 是否显示密码
      isShowPwd: false
    };
  },
  computed: {
    // 验证手机号是否正确
    isRightPhone(){
        return /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(this.phone)
    },
    
  },

  methods: {
    // 获取手机验证码
    async getPhoneCode(){
        this.countDownTime = 5
        const timeId = setInterval(() => {
            if(this.countDownTime <= 0){
              clearInterval(timeId)
            }else{
              this.countDownTime --
            }
        }, 1000)

      const result = await reqSMSCode(this.phone)
      if(result.code === 0){
        Toast ('验证码已发送')
      }else{
        // 停止计时
        this.countDownTime = 0
        Toast(result.msg)
      }
    },

    // 获取验证码
    getVerificationCode(){
        this.$refs.captcha.src = 'http://localhost:4000/captcha?time=' + Date.now()
    },

    // 登录【进行部分校验】
    async loginIn(){
      let result
      if(this.phoneLogin === true){
        const success = await this.$validator.validateAll(['phone', 'code'])
        if(success){
          result = await reqLoginBySMS(this.phone, this.code)
          // 无论成功还是失败，请求后清空倒计时
          this.countDownTime = 0
        }
      }else if(this.phoneLogin === false){
        const success = await this.$validator.validateAll(['username', 'pwd', 'captcha'])
        if(success){
          result = await reqLoginByUsername(this.username, this.pwd, this.captcha)
          // 判断是否需要更新图片验证码
          if(result.code === 1){
            this.getVerificationCode()
            this.captcha = ''
          }
        }
      }

      
       if(result.code === 0){
         const user = result.data
          // 保存登录的号码到vuex
          this.$store.dispatch('saveUser', user)

          // 跳转页面
          this.$router.replace('./profile')
       } else {
            MessageBox.alert(result.msg);
       }
      
    }
  }
}

</script>
<style lang='less' scoped>
  .loginContainer {
    width: 100%;
    height: 100%;
    background: #fff;

    .loginInner {
      padding-top: 60px;
      width: 80%;
      margin: 0 auto;

      .login_header {
        .login_logo {
          font-size: 40px;
          font-weight: bold;
          color: #02a774;
          text-align: center;
        }

        .login_header_title {
          padding-top: 40px;
          text-align: center;

          > a {
            color: #333;
            font-size: 14px;
            padding-bottom: 4px;

            &:first-child {
              margin-right: 40px;
            }

            &.on {
              color: #02a774;
              font-weight: 700;
              border-bottom: 2px solid #02a774;
            }
          }
        }
      }

      .login_content {
        > form {
          > div {
            display: none;

            &.on {
              display: block;
            }

            input {
              width: 100%;
              height: 100%;
              padding-left: 10px;
              box-sizing: border-box;
              border: 1px solid #ddd;
              border-radius: 4px;
              outline: 0;
              font: 400 14px Arial;

              &:focus {
                border: 1px solid #02a774;
              }
            }

            .login_message {
              position: relative;
              margin-top: 16px;
              height: 48px;
              font-size: 14px;
              background: #fff;

              .get_verification {
                position: absolute;
                top: 50%;
                right: 10px;
                transform: translateY(-50%);
                border: 0;
                color: #ccc;
                font-size: 14px;
                background: transparent;

                &.btn_code_active{
                    color: #333;
                }
              }
            }

            .login_verification {
              position: relative;
              margin-top: 16px;
              height: 48px;
              font-size: 14px;
              background: #fff;

              .switch_button {
                font-size: 12px;
                border: 1px solid #ddd;
                border-radius: 8px;
                transition: background-color 0.3s, border-color 0.3s;
                padding: 0 6px;
                width: 30px;
                height: 16px;
                line-height: 16px;
                color: #fff;
                position: absolute;
                top: 50%;
                right: 10px;
                transform: translateY(-50%);

                &.off {
                  background: #fff;

                  .switch_text {
                    float: right;
                    color: #ddd;
                  }
                }

                &.on {
                  background: #02a774;
                }

                .switch_circle {
                  position: absolute;
                  top: -1px;
                  left: -1px;
                  width: 16px;
                  height: 16px;
                  border: 1px solid #ddd;
                  border-radius: 50%;
                  background: #fff;
                  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
                  transition: transform 0.3s;

                  &.circle_right{
                    transform: translateX(27px);
                  }
                }
              }
            }

            .login_hint {
              margin-top: 12px;
              color: #999;
              font-size: 14px;
              line-height: 20px;

              > a {
                color: #02a774;
              }
            }
          }

          .login_submit {
            display: block;
            width: 100%;
            height: 42px;
            margin-top: 30px;
            border-radius: 4px;
            background: #4cd96f;
            color: #fff;
            text-align: center;
            font-size: 16px;
            line-height: 42px;
            border: 0;
          }
        }

        .about_us {
          display: block;
          font-size: 12px;
          margin-top: 20px;
          text-align: center;
          color: #999;
        }
      }

      .go_back {
        position: absolute;
        top: 5px;
        left: 5px;
        width: 30px;
        height: 30px;

        > .iconfont {
          font-size: 20px;
          color: #999;
        }
      }
    }
  }
</style>